// Initialization
// File ops
const HtmlWebpackPlugin = require('html-webpack-plugin')

// Folder ops
const path = require('path')
const webpack = require('webpack')

// Constants
const APP = path.join(__dirname, 'app')
const BUILD = path.join(__dirname, 'build')
const TEMPLATE = path.join(__dirname, 'app/templates/index.html')
const PORT = process.env.PORT || 3032

module.exports = {
  mode: 'development',
  // Paths and extensions
  entry: {
    app: APP,
  },
  output: {
    path: BUILD,
    filename: 'static/[name].js',
    publicPath: '/',
  },
  resolve: {
    extensions: ['.js', '.ts', '.jsx', '.css', '.scss'],
    alias: {
      'react-dom': '@hot-loader/react-dom',
    },
  },
  // Loaders for processing different file types
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: [
          'react-hot-loader/webpack',
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
            },
          },
          { loader: 'ifdef-loader', options: { HMR: true } },
        ],
        exclude: [/node_modules/],
        include: [APP],
      },
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'sass-loader',
            options: {
              includePaths: ['./node_modules'],
            },
          },
        ],
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.json$/,
        loader: 'json-loader',
        type: 'javascript/auto',
      },
      {
        test: /\.md$/,
        use: 'raw-loader',
      },
      {
        test: /\.ts$/,
        exclude: [/node_modules/],
        use: [
          {
            loader: 'ts-loader',
          },
        ],
      },
      {
        test: /\.(gif|png|jpe?g|svg|ico|webp)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'static/[hash].[ext]',
            },
          },
        ],
      },
    ],
  },

  // Source maps used for debugging information
  devtool: 'eval',
  // webpack-dev-server configuration
  devServer: {
    disableHostCheck: true,
    hot: true,
    historyApiFallback: true,

    stats: 'errors-only',

    // host: HOST,
    port: PORT,

    // CopyWebpackPlugin: This is required for webpack-dev-server.
    // The path should be an absolute path to your build destination.
    // outputPath: BUILD
  },

  // Webpack plugins
  plugins: [
    new HtmlWebpackPlugin({
      template: TEMPLATE,
      // JS placed at the bottom of the body element
      inject: 'body',
    }),
    new webpack.DllReferencePlugin({
      manifest: path.join(__dirname, 'build/vendorPackages.json'), // generated by webpack.dll.config.js
    }),
    new webpack.HotModuleReplacementPlugin(),
  ],
}
